import React, { useState, useEffect, useRef } from "react";
import { connect, useDispatch, history } from "umi";
import { Table, Tooltip, Typography, Pagination } from "antd";
const { Text } = Typography;
import "./index";
const TablePage = (props) => {
  const {
    keyId = "id",
    rowType = "checkbox",
    loading = false,
    columns = [],
    isSel = true,
    bordered = true,
    dataSource = [],
    summaryArr = [],
    onChange = () => {},
    pagination,
    paginationSize,
    total,
    pageNum = 1,
    pageSize = 10,
    pageSizeOptions = [10, 20, 50, 100],
    scroll = {
      y: 500,
    },
    // 鼠标移入
    onMouseEnter = () => {},
    onMouseLeave = () => {},
    onContextMenu = () => {},
    onDoubleClick = () => {},
    onClick = () => {},
  } = props;
  // 初始化数据 检查数据
  const initData = () => {
    if (!Array.isArray(dataSource)) {
      throw new Error(
        "XH-table组件警告:dataSource属性数据类型错误 -> 应为Array 传入却是" + typeof dataSource
      );
    }
    dataSource.forEach((t, index) => (t.key = index));

    return dataSource;
  };

  // 检查 columns 数据是否正确
  const initColumns = () => {
    if (!Array.isArray(columns)) {
      return [
        {
          title: `XH-table组件警告:columns属性数据类型错误 -> 应为Array 传入却是 ${typeof columns}`,
        },
      ];
    }
    columns.forEach((t, index) => {
      if (t.title == "操作") {
        t.fixed = "right";
        if (!t.width) {
          t.width = "320px";
        }
      } // 移出文字...
      t.ellipsis = {
        showTitle: true,
      };
      if (!t.width) {
        t.width = "100px";
        // 添加鼠标放上去 显示
        if (t.title != "操作" && !t.render) {
          t.render = (val) => (
            <Tooltip placement="topLeft" title={val}>
              {val}
            </Tooltip>
          );
        }
      }
    });

    return [
      {
        title: "序号",
        width: "80px",
        render: (text, record, index) => `${index + 1}`,
      },
      ...columns,
    ];
  };

  // 合计或者侧栏
  const summary = (val) => {
    return summaryArr.length > 0 ? (
      <>
        <Table.Summary.Row>
          <Table.Summary.Cell key={"index" + 0} index={0}>
            合计
          </Table.Summary.Cell>
          {/* 自动排序 以后再做 */}
          {initColumns().map((t, index) => {
            if (summaryArr.includes(t.dataIndex)) {
              return (
                <Table.Summary.Cell index={index} key={"summaryArr" + index}>
                  <Text type="danger">
                    {val.reduce((prev, curr) => {
                      const number = Number(prev) + Number(curr[t.dataIndex]);
                      return number.toFixed(2);
                    }, 0)}
                  </Text>
                </Table.Summary.Cell>
              );
            } else {
              return <Table.Summary.Cell index={index} key={index}></Table.Summary.Cell>;
            }
          })}
        </Table.Summary.Row>
      </>
    ) : (
      false
    );
  };

  useEffect(() => {
    pagination
      ? pagination({
          pageNum: pageNum,
          pageSize: pageSize,
        })
      : "";
  }, []);
  return (
    <div className="tableClass">
      <Table
        bordered={bordered}
        loading={loading}
        columns={initColumns()}
        rowSelection={
          isSel
            ? {
                onChange: (keys, item, type) => {
                  onChange({ keys, ids: item.map((t) => t[keyId]), list: item });
                },
                type: rowType,
              }
            : {}
        }
        scroll={scroll}
        pagination={false}
        dataSource={initData()}
        summary={(val) => summary(val)}
        onSelect={(val) => {}}
        onRow={(record) => {
          return {
            onClick: (val) => onClick, // 点击行
            onDoubleClick: (val) => onDoubleClick,
            onContextMenu: (val) => onContextMenu,
            onMouseEnter: onMouseEnter, // 鼠标移入行
            onMouseLeave: onMouseLeave,
          };
        }}
      />

      {total && total > 0 ? (
        <Pagination
          defaultCurrent={1}
          defaultPageSize={10}
          pageSizeOptions={pageSizeOptions}
          style={{ float: "right", marginTop: "20px" }}
          onChange={(num, size) => {
            pagination({
              pageNum: num,
              pageSize: size,
            });
          }}
          total={Number(total)}
        />
      ) : (
        ""
      )}
    </div>
  );
};
export default connect((state) => ({ user: state.user }))(TablePage);
